﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using QuanLyHocPhi.BLL;
using QuanLyHocPhi.GUI.DuLieu;
using NPOI.HSSF.UserModel;
using HorizontalAlignment = NPOI.SS.UserModel.HorizontalAlignment;
using System.IO;
using NPOI.SS.UserModel;
using QuanLyHocPhi.Model;

namespace QuanLyHocPhi.GUI.TacNghiep
{
    public partial class FormThongKeTheoCaNhan : FormBase
    {
        SinhVien selectedSinhVien;
        bool lockUpdate = false;
        long tongTien = 0;
        public string fileName = string.Format("{0}\\TEMPLATES\\MauThongKeCaNhan.xls",
        Application.StartupPath);

        public FormThongKeTheoCaNhan()
        {
            InitializeComponent();
            #region Cấu hình lưới quá trình nộp học phí
            gridQuaTrinh.AutoGenerateColumns = false;
            gridQuaTrinh.AllowDrop = false;
            gridQuaTrinh.AllowUserToAddRows = false;
            gridQuaTrinh.AllowUserToDeleteRows = false;
            colNgayNop.DataPropertyName = "NgayThuStr";
            colSoTien.DataPropertyName = "SoTienStr";
            colSoBienLai.DataPropertyName = "SoBienLai";
            colNoiDung.DataPropertyName = "NoiDungThu";
            colHocKy.DataPropertyName = "HocKyFull";
            #endregion

            #region Cấu hình lưới danh sách sinh viên
            gridDSSinhVien.AllowDrop = false;
            gridDSSinhVien.AllowUserToAddRows = false;
            gridDSSinhVien.AllowUserToDeleteRows = false;
            gridDSSinhVien.AutoGenerateColumns = false;
            colMaSV.DataPropertyName = "MaSinhVien";
            colHoDem.DataPropertyName = "HoDem";
            colTen.DataPropertyName = "Ten";
            #endregion

            LoadLoaiHinh();
        }

        private void InitComboSuggestion(ComboBox cmb, object datasource, string displayMember, string valueMember, string[] rangeDisplay)
        {
            cmb.AutoCompleteSource = AutoCompleteSource.CustomSource;
            cmb.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            cmb.DataSource = datasource;
            if (displayMember != null)
                cmb.DisplayMember = displayMember;
            if (valueMember != null)
                cmb.ValueMember = valueMember;
            // Xác định AutoCompleteCustomeSource
            var autoCompletSet = new AutoCompleteStringCollection();
            autoCompletSet.AddRange(rangeDisplay);
            cmb.AutoCompleteCustomSource = autoCompletSet;

            // Các tinh chỉnh nâng cao
            cmb.Leave += (oSender, oE) =>
            {
                var cbx = oSender as ComboBox;
                if (cbx == null)
                    return;
                cbx.BackColor = cbx.SelectedItem == null ? Color.LightPink : SystemColors.Window;
            };

            cmb.KeyDown += (oSender, oE) =>
            {
                if (oE.KeyCode != Keys.Enter)
                    return;
                var cbx = oSender as ComboBox;
                if (cbx == null)
                    return;
                cbx.BackColor = cbx.SelectedItem == null ? Color.LightPink : SystemColors.Window;
            };
        }

        void LoadQuaTrinhNopHocPhi()
        {
            bdsQuaTrinh.DataSource = null;
            gridQuaTrinh.DataSource = bdsQuaTrinh;
            if (bdsDsSinhVien.Current != null)
            {
                selectedSinhVien = bdsDsSinhVien.Current as SinhVien;
                if (selectedSinhVien != null)
                {
                    var ltPhieuThu = BizPhieuThu.GetListPhieuThuFor1SinhVien(selectedSinhVien.MaSinhVien, chkHocPhi.Checked, chkLePhi.Checked, ref tongTien);
                    bdsQuaTrinh.DataSource = ltPhieuThu;
                    gridQuaTrinh.DataSource = bdsQuaTrinh;
                    lbTongTien.Text = tongTien.ToString().FormatCurrency() + " đồng";
                    if (ltPhieuThu != null && ltPhieuThu.Count > 0)
                        bntXuatFile.Enabled = true;
                }
            }
        }

        private void bntXuatFile_Click(object sender, EventArgs e)
        {
            #region Tiền xử lý
            if (!File.Exists(fileName))
            {
                MessageBox.Show("File mẫu MauThongKeChuaNop.xls không tồn tại", "Lỗi");
                return;
            }
            FileStream fs = null;
            try
            {
                fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            }
            catch (Exception)
            {
                MessageBox.Show("File mẫu đang mở. Vui lòng đóng lại trước khi tiếp tục", "Lỗi");
                return;
            }
            #endregion

            #region Làm việc với file excel

            FormProgress frm = new FormProgress();
            frm.DoWork += delegate(object oSender, DoWorkEventArgs oE)
            {
                HSSFWorkbook templateWorkbook = new HSSFWorkbook(fs, true);

                #region Tạo style cho thông tin cs nhân
                var titleCellStyle = templateWorkbook.CreateCellStyle();
                titleCellStyle.Alignment = HorizontalAlignment.CENTER;
                var titleFont = templateWorkbook.CreateFont();
                titleFont.Boldweight = (short)FontBoldWeight.BOLD;
                titleFont.FontHeight = 236;
                titleFont.FontName = "Times New Roman";
                titleCellStyle.SetFont(titleFont);
                #endregion

                #region Tạo các style cho phần hiển thị nội dung
                var detailCellStyle = templateWorkbook.CreateCellStyle();
                detailCellStyle.Alignment = HorizontalAlignment.CENTER;
                detailCellStyle.BorderBottom = CellBorderType.DASHED;
                detailCellStyle.BorderLeft = CellBorderType.THIN;
                detailCellStyle.BorderRight = CellBorderType.THIN;
                var cellHoStyle = templateWorkbook.CreateCellStyle();
                cellHoStyle.BorderBottom = CellBorderType.DASHED;
                cellHoStyle.BorderLeft = CellBorderType.THIN;
                var cellTenStyle = templateWorkbook.CreateCellStyle();
                cellTenStyle.BorderBottom = CellBorderType.DASHED;
                cellTenStyle.BorderRight = CellBorderType.THIN;

                var detailCellStyleEnd = templateWorkbook.CreateCellStyle();
                detailCellStyleEnd.Alignment = HorizontalAlignment.CENTER;
                detailCellStyleEnd.BorderBottom = CellBorderType.THIN;
                detailCellStyleEnd.BorderLeft = CellBorderType.THIN;
                detailCellStyleEnd.BorderRight = CellBorderType.THIN;
                var cellHoStyleEnd = templateWorkbook.CreateCellStyle();
                cellHoStyleEnd.BorderBottom = CellBorderType.THIN;
                cellHoStyleEnd.BorderLeft = CellBorderType.THIN;
                var cellTenStyleEnd = templateWorkbook.CreateCellStyle();
                cellTenStyleEnd.BorderBottom = CellBorderType.THIN;
                cellTenStyleEnd.BorderRight = CellBorderType.THIN;

                var cellTongSoStyle = templateWorkbook.CreateCellStyle();
                var fontCellTongSo = templateWorkbook.CreateFont();
                fontCellTongSo.IsItalic = true;
                cellTongSoStyle.SetFont(fontCellTongSo);
                var cellBottomStyle = templateWorkbook.CreateCellStyle();
                cellBottomStyle.Alignment = HorizontalAlignment.CENTER;
                var fontCellBottomStyle = templateWorkbook.CreateFont();
                fontCellBottomStyle.Boldweight = (short)FontBoldWeight.BOLD;
                cellBottomStyle.SetFont(fontCellBottomStyle);
                #endregion

                #region Khởi tạo
                var sheet = templateWorkbook.GetSheet("sheet1");
                var indexRow = 5;
                var soLuong = gridQuaTrinh.Rows.Count;
                var row = sheet.GetRow(indexRow);
                #endregion

                #region Chèn phần thông tin cá nhân
                var cell = row.CreateCell(2);
                cell.SetCellValue(txtHoTen.Text);
                cell.CellStyle = titleCellStyle;
                cell = row.CreateCell(4);
                cell.SetCellValue(txtMSV.Text);
                cell.CellStyle = titleCellStyle;
                indexRow++;
                row = sheet.GetRow(indexRow);
                cell = row.CreateCell(2);
                cell.SetCellValue(txtLop.Text);
                cell.CellStyle = titleCellStyle;
                cell = row.CreateCell(4);
                cell.SetCellValue(txtLoaiHinh.Text);
                cell.CellStyle = titleCellStyle;
                #endregion

                #region Chèn nội dung danh sách sinh viên
                for (int j = 0; j < soLuong; j++)
                {
                    var dtRow = gridQuaTrinh.Rows[j];
                    row = sheet.CreateRow(j + 9);
                    //STT
                    cell = row.CreateCell(0);
                    cell.SetCellValue(j + 1);
                    cell.CellStyle = (j == (soLuong - 1)) ? detailCellStyleEnd : detailCellStyle;
                    for (int k = 0; k < 5; k++)
                    {
                        cell = row.CreateCell(k + 1);
                        cell.SetCellValue(dtRow.Cells[k].Value.ToString() != null ? dtRow.Cells[k].Value.ToString() : "");
                        cell.CellStyle = (j == (soLuong - 1)) ? detailCellStyleEnd : detailCellStyle;
                    }
                }
                #endregion

                #region Chèn phần bottom
                indexRow = soLuong + 9;
                row = sheet.CreateRow(indexRow);
                cell = row.CreateCell(4);
                cell.SetCellValue("Tổng");
                cell.CellStyle = titleCellStyle;
                cell = row.CreateCell(5);
                cell.SetCellValue(tongTien.ToString().FormatCurrency());
                cell.CellStyle = titleCellStyle;

                indexRow++;
                row = sheet.GetRow(indexRow);
                cell = row.CreateCell(1);
                cell.SetCellValue("Bằng chữ: ");
                cell.CellStyle = cellTongSoStyle;
                cell = row.CreateCell(2);
                cell.SetCellValue(tongTien.ToString().ConvertNum2Text() + " đồng");
                cell.CellStyle = cellTongSoStyle;

                indexRow++;
                row = sheet.GetRow(indexRow);
                try
                {
                    cell = row.CreateCell(3);
                }
                catch
                {
                    cell = row.GetCell(3);
                }
                cell.SetCellValue(string.Format("Huế, ngày {0:dd} tháng {0:MM} năm {0:yyyy}", DateTime.Now));
                cell.CellStyle = cellTongSoStyle;

                indexRow++;
                row = sheet.GetRow(indexRow);
                try
                {
                    cell = row.CreateCell(1);
                }
                catch
                {
                    cell = row.GetCell(1);
                }
                cell.SetCellValue(string.Format("Người thu"));
                cell.CellStyle = titleCellStyle;
                try
                {
                    cell = row.CreateCell(2);
                }
                catch
                {
                    cell = row.GetCell(2);
                }
                cell.SetCellValue(string.Format("Kế toán trưởng"));
                cell.CellStyle = titleCellStyle;
                try
                {
                    cell = row.CreateCell(4);
                }
                catch
                {
                    cell = row.GetCell(4);
                }
                cell.SetCellValue(string.Format("Trưởng đơn vị"));
                cell.CellStyle = titleCellStyle;

                indexRow += 6;
                row = sheet.CreateRow(indexRow);
                try
                {
                    cell = row.CreateCell(1);
                }
                catch
                {
                    cell = row.GetCell(1);
                }
                cell.SetCellValue(Program.NguoiSuDung.HoTen);
                cell.CellStyle = cellBottomStyle;

                var thongtin = BizNguoiSuDung.ThongTinDangKy();
                if (thongtin != null && thongtin.Length == 2)
                {
                    cell = row.CreateCell(2);
                    cell.SetCellValue(thongtin[0]);
                    cell.CellStyle = cellBottomStyle;

                    cell = row.CreateCell(4);
                    cell.SetCellValue(thongtin[1]);
                    cell.CellStyle = cellBottomStyle;
                }
                #endregion

                #region Lưu ra file Excel mới
                sheet.ForceFormulaRecalculation = true;

                if (!Directory.Exists(string.Format("{0}\\Temp", Application.StartupPath)))
                    Directory.CreateDirectory(string.Format("{0}\\Temp", Application.StartupPath));

                var tenfile = string.Format("{0}\\Temp\\{1}_{2}.xls", Application.StartupPath, txtHoTen.Text, txtLop.Text);
                try
                {
                    using (var fileData = new FileStream(tenfile, FileMode.Create))
                    {
                        templateWorkbook.Write(fileData);
                        fileData.Close();

                        #region Excel commented
                        #endregion
                        System.Diagnostics.Process.Start(tenfile);
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.ToString());
                }
                fs.Close();
                #endregion
            };
            #endregion

            #region On complete
            frm.RunWorkerCompleted += delegate(object oSender, RunWorkerCompletedEventArgs oE)
            {
                if (oE.Error != null)
                {
                    string msg = oE.Error.Message;
                    if (oE.Error.InnerException != null)
                        msg += oE.Error.InnerException.Message;
                    DialogUtils.ShowError(msg);
                }

            };
            #endregion

            frm.StartWorking(this);
        }

        private void LoadLoaiHinh()
        {
            lockUpdate = true;
            var ds = BizLoaiHinhDaoTao.GetListLoaiHinh();
            InitComboSuggestion(cmbLoaiHinh, ds, "TenLoaiHinh", "MaLoaiHinh", ds.Select(e => e.TenLoaiHinh).ToArray());
            //cmbLoaiHinh.DataSource = ds;
            //cmbLoaiHinh.DisplayMember = "TenLoaiHinh";
            //cmbLoaiHinh.ValueMember = "MaLoaiHinh";
            lockUpdate = false;
            LoadNamTuyenSinh();
        }

        private void LoadNamTuyenSinh()
        {
            lockUpdate = true;
            cmbNamTuyenSinh.DataSource = null;
            if ((cmbLoaiHinh.SelectedItem as LoaiHinhDaoTao) != null)
            {
                var ds = BizLoaiHinhDaoTao.GetList_NamTuyenSinh((cmbLoaiHinh.SelectedItem as LoaiHinhDaoTao).MaLoaiHinh);
                InitComboSuggestion(cmbNamTuyenSinh, ds, null, null, ds.ToArray());
                //cmbNamTuyenSinh.DataSource = ds;
                lockUpdate = false;
                LoadLopGoc();
            }
        }

        private void LoadLopGoc()
        {
            lockUpdate = true;
            cmbLop.DataSource = null;
            var ds = BizLopGoc.GetListLopGoc((cmbLoaiHinh.SelectedItem as LoaiHinhDaoTao).MaLoaiHinh, cmbNamTuyenSinh.SelectedItem as string);
            InitComboSuggestion(cmbLop, ds, "TenLopGoc", "MaLopGoc", ds.Select(e => e.TenLopGoc).ToArray());
            //cmbLop.DataSource = ds;
            //cmbLop.DisplayMember = "TenLopGoc";
            //cmbLop.ValueMember = "MaLopGoc";
            lockUpdate = false;
            LoadDanhSachSinhVien();
        }

        private void LoadDanhSachSinhVien()
        {
            lockUpdate = true;
            bdsDsSinhVien.DataSource = null;
            gridDSSinhVien.DataSource = bdsDsSinhVien;
            if (cmbLop.SelectedIndex != -1)
            {
                var ds = BizSinhVien.GetDanhSachSinhVien((cmbLop.SelectedItem as LopGoc).MaLopGoc);
                bdsDsSinhVien.DataSource = ds;
                gridDSSinhVien.DataSource = bdsDsSinhVien;
            }
            lockUpdate = false;
        }

        private void cmbLoaiHinh_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!lockUpdate)
            {
                LoadNamTuyenSinh();
            }
        }

        private void cmbNamTuyenSinh_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!lockUpdate)
            {
                LoadLopGoc();
            }
        }

        private void cmbLop_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!lockUpdate)
            {
                LoadDanhSachSinhVien();
                LoadThongTinSinhVien();
                LoadQuaTrinhNopHocPhi();
            }
        }

        private void bdsDsSinhVien_CurrentChanged(object sender, EventArgs e)
        {
            selectedSinhVien = null;
            if (bdsDsSinhVien.Current != null)
            {
                LoadThongTinSinhVien();
                LoadQuaTrinhNopHocPhi();
            }
        }
        private void LoadThongTinSinhVien()
        {
            if (bdsDsSinhVien.DataSource != null && (bdsDsSinhVien.Current as SinhVien) != null)
            {
                selectedSinhVien = bdsDsSinhVien.Current as SinhVien;
                if (selectedSinhVien != null)
                {
                    selectedSinhVien = BizSinhVien.GetSinhVienByMSV(selectedSinhVien.MaSinhVien);
                    txtMSV.Text = selectedSinhVien.MaSinhVien;
                    txtHoTen.Text = selectedSinhVien.HoDem + " " + selectedSinhVien.Ten;
                    txtLop.Text = selectedSinhVien.LopGoc.TenLopGoc;
                    txtLoaiHinh.Text = selectedSinhVien.LopGoc.LoaiHinhDaoTao.TenLoaiHinh;
                    txtNgaySinh.Text = selectedSinhVien.NgaySinh;
                }
            }
        }

        private void chkHocPhi_CheckedChanged(object sender, EventArgs e)
        {
            LoadQuaTrinhNopHocPhi();
        }

        private void chkLePhi_CheckedChanged(object sender, EventArgs e)
        {
            LoadQuaTrinhNopHocPhi();
        }
    }
}
